#服务器地址
#urlPre = 'http://visitveb.duapp.com/index.php'
urlPre = serverUrlPre.slice(0,-3)

$('#setPort').click( ->
	console.log 'set proxy'
	config =
		mode: "fixed_servers"
		rules:
			proxyForHttp:
				scheme:'http'
				host:$('#ip').val()
				port:parseInt $('#port').val()
			bypassList:[
				'localhost'
				'127.0.0.1'
				'visitveb.duap.com'
				'visitweb.allalla.com'
			]
	chrome.proxy.settings.set({value: config, scope: 'regular'},->
		console.log(config)
		$('#myshow').click()
	)
)

$('#noproxy').click noProxy

$('#myshow').click(->
	$('#show').load(this.href)
	false
)

show = (str)->
	old = $('#show').html()
	if Math.random() > 0.9
		oldArr = old.split('<br>')
		l = oldArr.length
		old = oldArr.slice(-10).join('<br>')

	$('#show').html(old + '<br />' + str)



#得到代理IP
ips = []
getProxyIp = ->
	if ips.length
		return ips.shift()
	handler =
		dataType:'json'
		timeout:5000
		error: ->
			ips = getProxyIp()
		success:(data)->
			ips = data
		async:off
	$.ajax "#{urlPre}?s=Check/getIp4check",handler
	if ips.length
		return ips.shift()
	else
		#桌面通知
		notification = webkitNotifications.createNotification 'images/notification.png','IP等级测定已经完成','OK'
		notification.show()
		noProxy()
		notification.onclick = ->
			notification.close()
		setTimeout(->
			notification.close()
		,120000)
		setTimeout loopValidateProxy,60000*10
		return off

#统计结果
stastics=
	0:0
	1:0
	2:0
	3:0
	4:0
	5:0
	6:0
	7:0
	err:0
	alive:0
	'':0
rankStartTime = new Date().getTime() #开始时间
#展示验证结果
showCheckProxy = (oneProxy,success=on)->
	oneProxy.agt_lasttime = new Date(oneProxy.agt_lasttime*1000).toLocaleDateString()
	className = if success then 'success' else 'error'
	html = "<li class='#{className}'>#{oneProxy.agt_lasttime} rank:#{oneProxy.agt_rank.big()} err:#{oneProxy.agt_err.big()}</li>"
	$('#checkResult').append $(html)
	document.body.scrollTop +=20
	
#统计耗时秒数的次数
timeCnt = {}
for i in [0..21]
	timeCnt[i]=0
bigTimeProxy = []
#验证一个代理是否可用
validateOneProxy = (data)->
	respUrlPre = "#{urlPre}?s=Check/setRank/agt_id/#{data.agt_id}"
	config =
		mode:'fixed_servers'
		rules:
			proxyForHttp:
				scheme:data.agt_type.toLowerCase()
				host:data.agt_ip
				port:parseInt data.agt_port
			bypassList:[
				'img*.taobaocdn.com','pics.taobaocdn.com'
				'g.tbcdn.cn','a.tbcdn.cn','l.tbcdn.cn'
				'img.taobao.com'
				'i.mmcdn.cn'
				'g.searc*.alicdn.com','gi*.md.alicdn.com'
				#aliyuncdn
				'uaction.aliyuncdn.com'
				#各省cdn
				'bj*.alicdn.com'
				'sh*.alicdn.com'
				'gd*.alicdn.com'
				'zj*.alicdn.com'
				'js*.alicdn.com'
				'fj*.alicdn.com'
				#自己
				'127.0.0.1','localhost'
				'visitveb.duapp.com'
				'visitweb.allalla.com'
				#server
				'developer.baidu.com','sma.duapp.com','*.bdimg.com'
			]
	setting =
		value:config
		scope:'regular'
	chrome.proxy.settings.set(setting,->
		checkUrl = 'http://visitweb.sinaapp.com?'
		iStartTime = +new Date()
		#记录统计信息
		doStatics = ->
			thisTime = Math.round((+new Date() - iStartTime)/1000)
			timeCnt[thisTime]++
			console.warn timeCnt
			if thisTime > 10
				bigTimeProxy.push data
				console.log bigTimeProxy
			
		handler=
			dataType:'json'
			#65秒超时
			timeout:16000
			#async:off
			complete:loopValidateProxy
			error:->
				#上报错误
				$.get("#{respUrlPre}/agt_err/1")
				stastics.err++
				showCheckProxy data,off
			success:(rank)->
				#设置等级
				$.get("#{respUrlPre}/agt_rank/#{rank}")
				showCheckProxy data
				stastics[rank]++
				if 0<rank<4
					doStatics()
		if data.agt_rank>0 and Math.random() > 0.3
			checkUrl = 'http://www.baidu.com/?x='
			handler.success = (html)->
				$.get("#{urlPre}?s=Check/alive/agt_id/#{data.agt_id}")
				stastics.alive++
				showCheckProxy data
				#提示信息
				doStatics()
			handler.dataType='html'
		$.ajax("#{checkUrl}#{new Date().getTime()}",handler)
	)
#循环设置代理
loopValidateProxy = ->
	if oneProxy=getProxyIp()
		validateOneProxy oneProxy
		showStasticsInfo()
checkLeft = undefined
getCheckLeft = ->
	if undefined == checkLeft
		$.getJSON "#{urlPre}?s=Check/getIp4checkCnt",(cnt)->
			checkLeft = cnt
	checkLeft
#展示统计信息
showStasticsInfo = ->
	usedTime = new Date().getTime() - rankStartTime
	html = ''
	checkCnt = 0
	for k,v of stastics
		unless v
			continue
		html += " <li>#{k}:#{v}</li>"
		checkCnt += v
	html += "<li>time used:#{Math.round(usedTime/1000)}s</li>"
	if getCheckLeft() != undefined
		html += "<li>process: #{checkCnt}/#{checkLeft}</li>"
	$('#stastics').html html




#设置区域
checkLocation = ->
	ret = ''
	ajaxHandler =
		dataType:'html'
		timeout:9000
		complete:->
			setTimeout checkLocation,20000 unless ret=='complete'
		success:(data)->
			if data =='complete'
				ret=data
				#桌面通知
				notification = webkitNotifications.createNotification 'images/notification.png','地区都完成了','IP所属地设置完成'
				notification.show()
				setTimeout(->
					notification.close()
				,600)
	$.ajax "#{urlPre}?s=Cron/checkLocationTb",ajaxHandler
if location.hash and '#location'==location.hash
	checkLocation()

#
$('#checkrank').click ->
	rankStartTime = new Date().getTime()
	noProxy()
	loopValidateProxy()

$('#checklocation').click checkLocation

if location.hash and location.hash=='#rank'
	noProxy()
	loopValidateProxy()
#debug切换
@switchDebug = ->
	chrome.storage.local.get 'debug',(item)->
		if item?.debug
			chrome.storage.local.remove 'debug',showDebugTxt
		else
			obj=
				debug:on
			chrome.storage.local.set obj,showDebugTxt
$('#debug').click switchDebug
showDebugTxt = ->
	chrome.storage.local.get 'debug',(item)->
		txt = '打开debug'
		if item?.debug
			txt = '关闭debug'
		$('#debug').html(txt)
showDebugTxt()
